package com.hsogoo.avatar.serialization.hessian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.hsogoo.avatar.serialization.Serializer;

/**
 * @Author huangsaigang
 * Created @2018/9/25.
 */
public class HessianSerializer implements Serializer {

    @Override
    public byte[] encode(Object obj) throws IOException {

        if(obj==null) throw new NullPointerException();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output ho = new Hessian2Output(os);
        ho.writeObject(obj);
        ho.flush();
        return os.toByteArray();
    }

    @Override
    public <T> T decode(byte[] buf, Class<T> clazz) throws IOException {
        if(buf==null) throw new NullPointerException();
        ByteArrayInputStream is = new ByteArrayInputStream(buf);
        Hessian2Input hi = new Hessian2Input(is);
        Object result = hi.readObject(clazz);
        return clazz.cast(result);
    }

}
